// 例子5

// ajax传统写法
var url1 = 'https://hq.tigerbrokers.com/fundamental/finance_calendar/getType/2017-02-26/2017-06-10';

function getJSON1(url, success, fail) {
    var XHR = new XMLHttpRequest();
    XHR.open('GET', url, true);
    XHR.send();

    XHR.onreadystatechange = function () {
        if (XHR.readyState == 4) {
            if (XHR.status == 200) {
                try {
                    var response = JSON.parse(XHR.responseText);
                    success(response);
                } catch (e) {
                    fail(e);
                }
            } else {
                fail(new Error(XHR.statusText));
            }
        }
    }
}

getJSON1(url1, function (resp) {
    console.log(resp);
}, function (err) {
    console.log(err);
})

// promise写法
var url2 = 'https://hq.tigerbrokers.com/fundamental/finance_calendar/getType/2017-02-26/2017-06-10';

// 封装一个get请求的方法
function getJSON2(url) {
    return new Promise(function (resolve, reject) {
        var XHR = new XMLHttpRequest();
        XHR.open('GET', url, true);
        XHR.send();

        XHR.onreadystatechange = function () {
            if (XHR.readyState == 4) {
                if (XHR.status == 200) {
                    try {
                        var response = JSON.parse(XHR.responseText);
                        resolve(response);
                    } catch (e) {
                        reject(e);
                    }
                } else {
                    reject(new Error(XHR.statusText));
                }
            }
        }
    })
}

getJSON2(url2).then(function (resp) {
    console.log(resp);
}).catch(function (err) {
    console.log(err)
});